//
//  LoginViewController.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/4/8.
//

import UIKit

class LoginViewController: CommonViewController {
    private let phoneView = UIView()

    private let loginBtn = UIButton(type:.custom)
    private let tip = UILabel()
    private let subTip = UILabel()
    private let ptype = UIButton(type: .custom)
    private let input = UITextField()
    fileprivate var phone:String = ""
    fileprivate var code:String = ""
    private var changebtn : UIButton?
    private var reloadbtn : UIButton?
    private var step = 0
    private var time = 60
  
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.view.backgroundColor = .white
        
        let nav = LoginNavgationView(navigationBarHeight)
        view.addSubview(nav)
        nav.snp.makeConstraints({
            $0.left.right.equalTo(0)
            $0.top.equalTo(UIApplication.shared.statusBarFrame.height)
            $0.height.equalTo(navigationBarHeight)
        })
        view.addSubview(tip)

        let iconImage = UIImageView(image: UIImage(named: "AppIcon"))
        view.addSubview(iconImage)
        iconImage.snp.makeConstraints({
            $0.left.equalToSuperview().inset(30)
            $0.top.equalToSuperview().inset(100)
            $0.height.width.equalTo(tip.snp.height)
        })
        tip.text = "手机登录"
        tip.font = Font_Size_20
        tip.snp.makeConstraints {
            $0.left.equalTo(iconImage.snp.right).offset(5)
            $0.top.equalToSuperview().inset(100)
        }
        
        subTip.text = "未注册的手机号验证通过后将自动注册"
        subTip.font = Font_Size_12
        subTip.textColor = B999_TITLE_COLOR
        view.addSubview(subTip)
        subTip.snp.makeConstraints({
            $0.left.equalTo(iconImage)
            $0.top.equalTo(tip.snp.bottom).offset(10)
        })
        
        view.addSubview(phoneView)
        phoneView.snp.makeConstraints({
            $0.left.equalToSuperview().inset(30)
            $0.right.equalToSuperview().inset(30)
            $0.top.equalTo(subTip.snp.bottom).offset(50)
            $0.height.equalTo(50)
        })
        
        ptype.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        ptype.setTitleColor(.black, for: .normal)
        ptype.setTitle("+86^", for: .normal)
        phoneView.addSubview(ptype)
        ptype.snp.makeConstraints({
            $0.centerY.left.equalToSuperview()
            $0.width.equalTo(60)
        })
        
        input.delegate = self
        input.keyboardType = .numberPad
        input.clearButtonMode = .whileEditing
        input.placeholder = "手机号码"
        input.font = UIFont.boldSystemFont(ofSize: 18)
        phoneView.addSubview(input)
        input.snp.makeConstraints({
            $0.right.equalToSuperview().inset(10)
            $0.centerY.equalToSuperview()
            $0.left.equalTo(ptype.snp.right).offset(15)
        })
        let line = UIView()
        
        phoneView.addSubview(line)
        line.backgroundColor = .lightGray
        line.snp.makeConstraints({
            $0.left.right.bottom.equalTo(0)
            $0.height.equalTo(0.5)
        })
        
        view.addSubview(loginBtn)
        loginBtn.titleLabel?.font = Font_Size_14
        loginBtn.layer.cornerRadius = 5
        loginBtn.clipsToBounds = true
        loginBtn.setBackgroundImage(RED_COLOR.toImage(), for: .normal)
        loginBtn.isEnabled = false
        loginBtn.setTitle("获取验证码并同意协议",for:.normal)
        loginBtn.addTarget(self, action: #selector(getPhoneCode), for: .touchUpInside)
        loginBtn.snp.makeConstraints({
            $0.left.right.equalTo(phoneView)
            $0.top.equalTo(phoneView.snp.bottom).offset(15)
            $0.height.equalTo(40)
        })
        
        let protocolView = UIView()
        view.addSubview(protocolView)
        protocolView.snp.makeConstraints({
            $0.centerX.equalToSuperview()
            $0.top.equalTo(loginBtn.snp.bottom).offset(30)
            $0.height.equalTo(35)
        })
        
        let pTip1 = UILabel()
        pTip1.textColor = B999_TITLE_COLOR
        pTip1.text = "已阅读"
        pTip1.font = Font_Size_12
        protocolView.addSubview(pTip1)
        pTip1.snp.makeConstraints({
            $0.centerY.left.equalToSuperview()
        })
        
        let userProtocol = UIButton()
        userProtocol.addTarget(self, action: #selector(userProtocolClick), for: .touchUpInside)
        userProtocol.titleLabel?.font = Font_Size_12
        userProtocol.setTitleColor(B999_TITLE_COLOR, for: .normal)
        userProtocol.setTitle("<用户协议>",for:.normal)
        protocolView.addSubview(userProtocol)
        userProtocol.snp.makeConstraints({
            $0.left.equalTo(pTip1.snp.right)
            $0.centerY.equalTo(pTip1)
        })
        let pTip2 = UILabel()
        pTip2.font = Font_Size_12
        pTip2.text = "和"
        pTip2.textColor = B999_TITLE_COLOR
        protocolView.addSubview(pTip2)
        pTip2.snp.makeConstraints({
            $0.centerY.equalTo(userProtocol)
            $0.left.equalTo(userProtocol.snp.right)
        })
        let privateProtocol = UIButton()
        privateProtocol.addTarget(self, action: #selector(privateProtocolClick), for: .touchUpInside)
        privateProtocol.titleLabel?.font = Font_Size_12
        privateProtocol.setTitleColor(B999_TITLE_COLOR, for: .normal)
        privateProtocol.setTitle("<隐私协议>",for:.normal)
        protocolView.addSubview(privateProtocol)
        privateProtocol.snp.makeConstraints({
            $0.left.equalTo(pTip2.snp.right)
            $0.centerY.equalTo(pTip2)
            $0.right.equalToSuperview()
        })
        
        let bottomView = UIView()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints({
            $0.height.equalTo(40)
            $0.left.right.equalTo(0)
            $0.bottom.equalToSuperview().inset(30)
        })
        
        let helpbtn = UIButton(type: .custom)
        helpbtn.titleLabel?.font = Font_Size_12
        helpbtn.addTarget(self, action: #selector(helpClick), for: .touchUpInside)
        helpbtn.setTitleColor(B000_COLOR, for: .normal)
        helpbtn.setTitle("遇到问题", for: .normal)
        bottomView.addSubview(helpbtn)
        helpbtn.snp.makeConstraints({
            $0.center.equalToSuperview()
        })
        hideKeyboardWhenTappedAround()
    }
    func setNavicationBar()->UINavigationController?{
        if self.navigationController == nil {
            return UINavigationController.init(rootViewController: self)
        }
        return self.navigationController
    }
    @objc func userProtocolClick(){
        let vc = LoadWebViewController()
        vc.url = "https://www.toutiao.com"
        self.pushViewController(vc, animated: true)
    }
    @objc func privateProtocolClick(){
        let vc = LoadWebViewController()
        vc.url = "https://www.toutiao.com"
        self.pushViewController(vc, animated: true)
    }
    @objc func helpClick(){
        let vc = LoadWebViewController()
        vc.url = "https://www.toutiao.com"
        self.pushViewController(vc, animated: true)
    }
    @objc func getPhoneCode(){
        if(step == 1){
            // 登录接口
           
            DataManager.login = true
            NotificationMananger.post(.LoginCompletion)
            self.dismiss(animated: true) {
                
            }
        }else{
            SystemLog(phone)
            step = 1
            nextStep()
        }
    }
    // 获取验证码成功，进入下一步
    func nextStep() {
        if(changebtn == nil){
            changebtn = UIButton(type: .custom)
            view.addSubview(changebtn!)
            changebtn?.setTitle("修改", for: .normal)
            changebtn?.contentEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
            changebtn?.setTitleColor(UIColor.lightGray, for: .normal)
            changebtn?.snp.makeConstraints({
                $0.centerY.equalTo(subTip)
                $0.left.equalTo(subTip.snp.right).offset(5)
            })
            changebtn?.addTarget(self, action: #selector(backStep), for: .touchUpInside)
            changebtn?.titleLabel?.font = Font_Size_12
        }else{
            changebtn?.isHidden = false
        }
        if(reloadbtn == nil){
            reloadbtn = UIButton(type: .custom)
            phoneView.addSubview(reloadbtn!)
            reloadbtn?.setTitleColor(.lightGray, for: .normal)
            reloadbtn?.setTitle("重新获取\(time)s", for: .normal)
            reloadbtn?.contentEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
            reloadbtn?.setTitleColor(UIColor.lightGray, for: .normal)
            reloadbtn?.snp.makeConstraints({
                $0.centerY.right.equalToSuperview()
                $0.width.equalTo(100)
                $0.right.equalToSuperview()
            })
            reloadbtn?.titleLabel?.font = Font_Size_12
            reloadbtn?.addTarget(self, action: #selector(reloadClick), for: .touchUpInside)
        }else{
            reloadbtn?.isHidden = false
            reloadbtn?.snp.makeConstraints({
                $0.left.equalTo(input.snp.right)
                $0.centerY.right.equalToSuperview()
            })
        }
        reloadbtn?.isEnabled = false
        loginBtn.setTitle("下一步", for: .normal)
        loginBtn.isEnabled = false
        tip.text = "输入验证码"
        subTip.text = "验证码已发送至 \(phone) "
        ptype.isHidden = true
        input.text = ""
        input.placeholder = ""
        step = 1
        ptype.snp.removeConstraints()
        input.snp.remakeConstraints({
            $0.right.equalTo((reloadbtn?.snp.left)!).offset(10)
            $0.centerY.equalToSuperview()
            $0.left.equalToSuperview()
        })
        self.timer()
    }
    // 修改手机号,返回上一步
    @objc func backStep() {
        loginBtn.setTitle("获取验证码并同意协议",for:.normal)
        loginBtn.isEnabled = true
        tip.text = "手机登录"
        subTip.text = "未注册的手机号验证通过后将自动注册"
        changebtn?.isHidden = true
        ptype.isHidden = false
        reloadbtn?.isHidden = true
        input.text = phone
        input.placeholder = "手机号码"
        step = 0
        reloadbtn?.snp.removeConstraints()
        ptype.snp.makeConstraints({
            $0.centerY.left.equalToSuperview()
            $0.width.equalTo(60)
        })
        input.snp.remakeConstraints({
            $0.right.equalToSuperview().inset(10)
            $0.centerY.equalToSuperview()
            $0.left.equalTo(ptype.snp.right).offset(15)
        })
    }
    @objc func reloadClick(){
        timer()
    }
    func timer()  {
        if(step == 1){
            SystemLog(time)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
                if(self.time == 0){
                    self.reloadbtn?.isEnabled = true
                    self.time = 60
                }else{
                    self.time -= 1
                    self.reloadbtn?.setTitle("重新获取\(self.time)s", for: .normal)
                    self.timer()
                }
            }
        }else{
            self.time = 60
            self.reloadbtn?.setTitle("重新获取\(self.time)s", for: .normal)
            self.reloadbtn?.isEnabled = false
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 隐藏导航栏背景颜色
        self.navigationController?.navigationBar.isHidden = true
       
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // 隐藏导航栏背景颜色
        self.navigationController?.navigationBar.isHidden = false
       
       
    }

}
extension LoginViewController:UITextFieldDelegate{
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        SystemLog(range)
//        SystemLog(string)
        if(range.length == 0){
            if(Int(string) == nil){
                return false
            }
        }
        if(range.location == (step == 1 ? 4:11)){
            return false
        }
        if(range.location == (step == 1 ? 3:10) && range.length == 0){
            loginBtn.isEnabled = true
            if(step == 1){
                self.code = textField.text!+string
                // 输入完成，自动调用登录接口
            }else{
                self.phone = textField.text!+string
            }
        }else{
            loginBtn.isEnabled = false
        }
        return true
    }
}
